﻿//+-------------------------------------------------------------------------------------------------------------------------------------------------------
//
//Description: ResourceExtensionDataPackageViewModel
//Author: Aravind Ramarathinam (aravr@microsoft.com)
//
//Copyright © Microsoft Corporation
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
//You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
//INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 
//See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
// 
//--------------------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using VmroleAuthor.Commands;
using VmroleAuthor.Models;

namespace VmroleAuthor.ViewModels
{
    public class ResourceExtensionDataPackageViewModel : TreeViewItemViewModel, IDataErrorInfo, IProduceValidationResults
    {
        private DataPackage dataPackage;
        private readonly VmRoleResourceExtensionViewModel vmRoleResourceExtensionViewModel;
        private readonly ObservableCollection<ExternalPayloadViewModel> externalPayloadViewModels;

        public const string DefaultDataPackageLocation = "src";
        public const string DefaultDataPackageVersion = "1.0.0.0";

        public static class PropertyNames
        {
            public const string Summary = "Summary";
            public const string Location = "Location";
            public const string Version = "Version";       
        }

        public ResourceExtensionDataPackageViewModel(
            DataPackage dataPackage, 
            VmRoleResourceExtensionViewModel resourceExtensionViewModel)
            : base(resourceExtensionViewModel, true)
        {
            this.dataPackage = dataPackage;            
            this.vmRoleResourceExtensionViewModel = resourceExtensionViewModel;

            this.externalPayloadViewModels = new ObservableCollection<ExternalPayloadViewModel>();
            if (this.dataPackage != null && this.dataPackage.ExternalPayload != null)
            {
                foreach (ExternalPayload externalPayload in this.dataPackage.ExternalPayload)
                {
                    this.externalPayloadViewModels.Add(new ExternalPayloadViewModel(externalPayload));
                }
            }

           this.AddExternalPayloadCommand = new RelayCommand(
           param => this.AddExternalPayload(),
           param => this.CanAddExternalPayload());

            this.DeleteExternalPayloadCommand = new RelayCommand(
                param => this.DeleteExternalPayload((ExternalPayloadViewModel)param),
                param => this.CanDeleteExternalPayload((ExternalPayloadViewModel)param));    

            this.ValidationResults = new ObservableCollection<CloudServiceModelValidationResult>();
        }

        public string Summary
        {
            get
            {
               if (this.dataPackage ==null || string.IsNullOrEmpty(this.dataPackage.Location))
               {
                   return "DataPackage (Not Set)";
               }
                return "DataPackage (" + this.dataPackage.Location + ")";
            }
        }

        public string Location
        {
            get
            {
                return this.dataPackage != null ? this.dataPackage.Location : string.Empty;
            }
            set             
            {
                if (string.IsNullOrEmpty(value) && string.IsNullOrEmpty(this.Version))
                {
                    this.dataPackage = null;
                    this.vmRoleResourceExtensionViewModel.ResourceExtensionDefinition.DataPackage = null;
                }
                else
                {
                    if (this.dataPackage == null)
                    {
                        this.dataPackage = new DataPackage();
                        this.vmRoleResourceExtensionViewModel.ResourceExtensionDefinition.DataPackage = this.dataPackage;
                    }
                    string previousLocation = this.dataPackage.Location;
                    this.dataPackage.Location = value;
                    if (!string.IsNullOrEmpty(this.dataPackage.Location) &&
                        this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo != null &&
                        this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir != null)
                    {
                        string datapackageLoc = Path.Combine(this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir, this.dataPackage.Location);
                        if (Directory.Exists(this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir) && !Directory.Exists(datapackageLoc))
                        {
                            Directory.CreateDirectory(datapackageLoc);
                        }
                    }

                    if (!string.IsNullOrEmpty(previousLocation) &&
                         this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo != null &&
                         this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir != null &&
                          string.Compare(this.dataPackage.Location, previousLocation, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        string oldDatapackageLoc = Path.Combine(this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir, previousLocation);
                        if (Directory.Exists(this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir) && Directory.Exists(oldDatapackageLoc))
                        {
                            Directory.Delete(oldDatapackageLoc, true);
                        }
                    }
                }                
               
                this.OnPropertyChanged(PropertyNames.Location);
                this.OnPropertyChanged(PropertyNames.Version);
                this.OnPropertyChanged(PropertyNames.Summary);
            }
        }

        public string Version
        {
            get
            {
                return this.dataPackage != null ? this.dataPackage.Version : string.Empty;
            }
            set
            {
                if (string.IsNullOrEmpty(value) && string.IsNullOrEmpty(this.Location))
                {
                    this.dataPackage = null;
                    this.vmRoleResourceExtensionViewModel.ResourceExtensionDefinition.DataPackage = null;
                }
                else
                {
                    if (this.dataPackage == null)
                    {
                        this.dataPackage = new DataPackage();
                        this.vmRoleResourceExtensionViewModel.ResourceExtensionDefinition.DataPackage = this.dataPackage;
                    }
                    this.dataPackage.Version = value;
                }                
                this.OnPropertyChanged(PropertyNames.Version);
                this.OnPropertyChanged(PropertyNames.Location);
            }
        }

        public ObservableCollection<ExternalPayloadViewModel> ExternalPayload
        {
            get { return this.externalPayloadViewModels; }
        }

        public ICommand AddExternalPayloadCommand
        {
            get;
            private set;
        }

        public ICommand DeleteExternalPayloadCommand
        {
            get;
            private set;
        }

        public bool CanAddExternalPayload()
        {
            return true;
        }

        public ExternalPayloadViewModel AddExternalPayload()
        {     
            if (this.dataPackage == null)
            {
                this.dataPackage = new DataPackage();
                this.vmRoleResourceExtensionViewModel.ResourceExtensionDefinition.DataPackage = this.dataPackage;
                this.vmRoleResourceExtensionViewModel.ResourceExtensionDataPackageViewModel.Location = ResourceExtensionDataPackageViewModel.DefaultDataPackageLocation;
                this.vmRoleResourceExtensionViewModel.ResourceExtensionDataPackageViewModel.Version = ResourceExtensionDataPackageViewModel.DefaultDataPackageVersion;
                try
                {
                    string pkgSrc = System.IO.Path.Combine(this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir,ResourceExtensionDataPackageViewModel.DefaultDataPackageLocation);
                    System.IO.Directory.CreateDirectory(pkgSrc);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to create data package source directory: " + ex.Message, DefinitionViewModel.ToolHeader);
                }
            }
            if (this.dataPackage.ExternalPayload == null)
            {
                this.dataPackage.ExternalPayload = new List<ExternalPayload>();
            }
            ExternalPayload env = new ExternalPayload();
            this.dataPackage.ExternalPayload.Add(env);
            var extPayloadViewModel = new ExternalPayloadViewModel(env);
            this.externalPayloadViewModels.Add(extPayloadViewModel);
            return extPayloadViewModel;
        }

        public bool CanDeleteExternalPayload(ExternalPayloadViewModel externalPayloadViewModel)
        {
            return true;
        }

        public void DeleteExternalPayload(ExternalPayloadViewModel externalPayloadViewModel)
        {
            if (externalPayloadViewModel != null)
            {
                externalPayloadViewModel.Cleanup();
                if (this.dataPackage.ExternalPayload != null)
                {
                    this.dataPackage.ExternalPayload.Remove(externalPayloadViewModel.ExternalPayload);
                }
                this.externalPayloadViewModels.Remove(externalPayloadViewModel);
            }
        }


        public void DeleteExternalPayloadStartingWithPrefix(string prefix)
        {
            if (string.IsNullOrEmpty(prefix))
            {
                return;
            }          
            for (int i = this.externalPayloadViewModels.Count -1 ; i >= 0; i--)
            {
                if (this.externalPayloadViewModels[i].RelativePath.StartsWith(prefix, StringComparison.Ordinal) ||
                    this.externalPayloadViewModels[i].RelativePath.StartsWith("./" + prefix, StringComparison.Ordinal))
                {
                    this.dataPackage.ExternalPayload.Remove(this.externalPayloadViewModels[i].ExternalPayload);
                    this.externalPayloadViewModels.RemoveAt(i);                    
                }
            }
        }

        public bool ExternalPayloadStartingWithPrefixExists(string prefix)
        {
            if (string.IsNullOrEmpty(prefix))
            {
                return false;
            }
            for (int i = this.externalPayloadViewModels.Count - 1; i >= 0; i--)
            {
                if (this.externalPayloadViewModels[i].RelativePath.StartsWith(prefix, StringComparison.Ordinal) ||
                    this.externalPayloadViewModels[i].RelativePath.StartsWith("./" + prefix, StringComparison.Ordinal))
                {
                   return true;
                }
            }
            return false;
        }


        public bool ContainsExternalPayloadStartingWithPrefix(string prefix)
        {
            if (string.IsNullOrEmpty(prefix))
            {
                return false;
            }
            for (int i = this.externalPayloadViewModels.Count - 1; i >= 0; i--)
            {
                if (this.externalPayloadViewModels[i].RelativePath.StartsWith(prefix, StringComparison.Ordinal) ||
                    this.externalPayloadViewModels[i].RelativePath.StartsWith("./" + prefix, StringComparison.Ordinal))
                {
                    return true;
                }
            }
            return false;
        }

        protected override void LoadChildren()
        {
           // No children                          
        }

        public string this[string propertyName]
        {
            get
            {
                if (this.dataPackage == null)
                {
                    return null;
                }
                string error = null;                
                switch (propertyName)
                {
                    case PropertyNames.Location:
                        if (this.dataPackage != null)
                        {
                            error = ParameterizationHelper.ValidateCannotBeParameterizedBySpecification(this.Location);
                            if (error == null)
                            {
                                if (this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo == null)
                                {
                                    error = "StorageInfo not set";
                                }
                                else
                                {
                                    string fullPath = Path.Combine(this.vmRoleResourceExtensionViewModel.ResourceExtensionStorageInfo.WorkingDir, this.Location);
                                    if (!Directory.Exists(fullPath))
                                    {
                                        //Check if all payload items are external.
                                        //so essentially you should NOT get this error message, if all app payload items are external
                                        //if some are external and some are internal, src folder is still needed (for internal)
                                        bool anyInternal = this.vmRoleResourceExtensionViewModel.ApplicationProvileViewModel.ApplicationPayloads.Any(appPayloadViewModel => !appPayloadViewModel.IsExternal);
                                        if (
                                            this.vmRoleResourceExtensionViewModel.ApplicationProvileViewModel.ApplicationPayloads != null &&
                                            this.vmRoleResourceExtensionViewModel.ApplicationProvileViewModel.ApplicationPayloads.Count > 0 &&
                                            anyInternal
                                            )
                                        {
                                            error = "Location directory does not exist in storage working directory: " + this.Location;
                                        }                                        
                                    }
                                }

                            }
                        }                       
                        break;
                    case PropertyNames.Version:
                        if (this.dataPackage != null)
                        {
                            error = ValidationHelper.ValidateVersionFormat(this.Version);
                        }                        
                        break;
                }                           
                return error;
            }           
        }

        public string Error { get; set; }

        public ObservableCollection<CloudServiceModelValidationResult> ValidationResults { get; private set; }

        public void UpdateValidationResults()
        {
            ModelValidationResultsHelper.UpdateValidationResults(this, typeof(PropertyNames));
            //Add any other cross-field validations error            
        }    
    }   
}
